import request from '@/utils/request';
import { requestWrapper, randomDate, randomInt, randomPick } from '@/utils/mock';
import { useMock } from '@/utils/request';

// 获取部门列表
export function getDeptList(params) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/system/dept/list',
      method: 'get',
      params
    }),
    // 模拟数据
    () => {
      // 创建一些顶级部门
      const topDepts = Array.from({ length: 3 }, (_, index) => ({
        deptId: index + 1,
        parentId: 0,
        deptName: `部门${index + 1}`,
        orderNum: index + 1,
        leader: `负责人${index + 1}`,
        phone: `138${randomInt(10000000, 99999999)}`,
        email: `dept${index + 1}@example.com`,
        status: randomPick(['0', '1']),
        createTime: randomDate(-30),
        children: []
      }));

      // 为每个顶级部门创建子部门
      topDepts.forEach((dept, deptIndex) => {
        const childCount = randomInt(2, 4);
        const children = Array.from({ length: childCount }, (_, index) => {
          const deptId = (deptIndex + 1) * 10 + index + 1;
          return {
            deptId,
            parentId: dept.deptId,
            deptName: `子部门${deptId}`,
            orderNum: index + 1,
            leader: `负责人${deptId}`,
            phone: `138${randomInt(10000000, 99999999)}`,
            email: `subdept${deptId}@example.com`,
            status: randomPick(['0', '1']),
            createTime: randomDate(-30)
          };
        });
        dept.children = children;
      });

      // 处理搜索条件
      let filteredDepts = [...topDepts];

      if (params) {
        if (params.deptName) {
          // 实现带有子部门匹配的搜索
          filteredDepts = filteredDepts.filter(parent => {
            // 父部门名称匹配
            if (parent.deptName.includes(params.deptName)) {
              return true;
            }
            
            // 子部门名称匹配，保留匹配的子部门
            const matchedChildren = parent.children.filter(child => 
              child.deptName.includes(params.deptName)
            );
            
            if (matchedChildren.length > 0) {
              parent.children = matchedChildren;
              return true;
            }
            
            return false;
          });
        }
        
        if (params.status !== undefined && params.status !== '') {
          filteredDepts = filteredDepts.filter(parent => {
            if (parent.status !== params.status) {
              return false;
            }
            
            // 过滤子部门
            parent.children = parent.children.filter(child => child.status === params.status);
            
            return true;
          });
        }
      }

      return filteredDepts;
    }
  );
}

// 获取部门详情
export function getDeptDetail(deptId) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/system/dept/${deptId}`,
      method: 'get'
    }),
    // 模拟数据
    {
      deptId,
      parentId: deptId > 10 ? Math.floor(deptId / 10) : 0,
      deptName: deptId > 10 ? `子部门${deptId}` : `部门${deptId}`,
      orderNum: deptId % 10 || deptId,
      leader: `负责人${deptId}`,
      phone: `138${randomInt(10000000, 99999999)}`,
      email: `dept${deptId}@example.com`,
      status: '1',
      remark: `部门${deptId}的备注信息`,
      createTime: randomDate(-30),
      updateTime: randomDate(-10)
    }
  );
}

// 新增部门
export function addDept(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/system/dept',
      method: 'post',
      data
    }),
    // 模拟数据
    {
      deptId: randomInt(100, 999)
    }
  );
}

// 更新部门
export function updateDept(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/system/dept',
      method: 'put',
      data
    }),
    // 模拟数据
    null
  );
}

// 删除部门
export function deleteDept(deptId) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/system/dept/${deptId}`,
      method: 'delete'
    }),
    // 模拟数据
    null
  );
}

// 获取部门树形结构
export function getDeptTreeSelect() {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/system/dept/tree-select',
      method: 'get'
    }),
    // 模拟数据
    [
      {
        id: 1,
        label: '总公司',
        children: [
          {
            id: 11,
            label: '研发部门',
            children: []
          },
          {
            id: 12,
            label: '市场部门',
            children: []
          }
        ]
      },
      {
        id: 2,
        label: '分公司',
        children: [
          {
            id: 21,
            label: '技术部门',
            children: []
          }
        ]
      }
    ]
  );
}

// 生成一致的部门树结构
const generateDeptTree = () => {
  return [
    {
      deptId: 1,
      deptName: '总公司',
      children: [
        {
          deptId: 11,
          deptName: '研发部门',
          parentId: 1
        },
        {
          deptId: 12,
          deptName: '市场部门',
          parentId: 1
        }
      ]
    },
    {
      deptId: 2,
      deptName: '分公司',
      children: [
        {
          deptId: 21,
          deptName: '技术部门',
          parentId: 2
        },
        {
          deptId: 22,
          deptName: '运营部门',
          parentId: 2
        }
      ]
    }
  ];
};

// 获取部门树结构用于岗位管理
export function getDeptTreeList() {
  console.log('是否启用模拟模式:', useMock);
  
  // 为了确保数据格式一致，手动处理mock模式
  if (useMock) {
    console.log('使用模拟数据');
    return Promise.resolve({
      code: 200,
      msg: '操作成功(模拟数据)',
      data: generateDeptTree()
    });
  }
  
  // 真实API请求
  return request({
    url: '/system/dept/tree',
    method: 'get'
  });
}

// 更新部门状态
export function updateDeptStatus(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/system/dept/status',
      method: 'put',
      data
    }),
    // 模拟数据
    null
  );
} 